﻿using StackExchange.Redis;
using System;

namespace Redis.Library
{
    /// <summary>
    /// redis链接操作
    /// </summary>
    public  class RedisConnection : IDisposable
    {

        //具体数据库片
        private readonly int dbIndex;

        //链接名称
        private readonly string sectionName;

        //与redis服务关联的对象
        private ConnectionMultiplexer cnn;

        /// <summary>
        /// 当前连接池
        /// </summary>
        /// <returns></returns>
        internal RedisConnectPool Pool { get; private set; }

        /// <summary>
        /// redis连接
        /// </summary>
        /// <param name="sectionName"></param>
        /// <param name="dbIndex"></param>
        public RedisConnection(string sectionName, int dbIndex)
        {
            this.sectionName = sectionName;
            this.dbIndex = dbIndex;
            this.Pool = RedisConnectPoolManager.GetPool(sectionName);
            this.cnn = this.Pool.GetConnection();
        }

        /// <summary>
        /// 释放连接
        /// </summary>
        public void Dispose()
        {
            cnn = null;
        }

        /// <summary>
        /// 获取Database
        /// </summary>
        /// <returns></returns>
        public IDatabase GetDatabase()
        {
            return cnn.GetDatabase(dbIndex);
        }

        /// <summary>
        /// 从连接池中取出下一个连接并获得他的database（队列中用到） 
        /// </summary>
        /// <returns></returns>
        public IDatabase GetDatabaseFromNextConnection()
        {
            return Pool.GetConnection().GetDatabase(dbIndex);
        }

        /// <summary>
        /// 获取服务器信息
        /// </summary>
        /// <returns></returns>
        public string GetServerInfo()
        {
            var info = string.Empty;
            try
            {
                var eps = cnn.GetEndPoints(true);
                if (eps != null && eps.Length > 0)
                {
                    foreach (var ep in cnn.GetEndPoints(true))
                    {
                        info += $"{ep.AddressFamily.ToString()}-{cnn.GetServer(ep).EndPoint}\n";
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            //Catch(() =>
            //{
               
            //},
            //ex =>
            //{
            //    throw new Exception($"获取服务器信息失败", ex);
            //});
            return info;
        }

    }
}
